import { useState, useEffect, useRef } from 'preact/hooks';
import { isConnected } from '../app';

export default function BuzzerControl() {
  const [frequency, setFrequency] = useState(1000);
  const [frequencyInput, setFrequencyInput] = useState('1000');
  const [isPlaying, setIsPlaying] = useState(false);
  const pendingStopOnUnmountRef = useRef(false);

  const playTone = async (freq) => {
    if (!isConnected.value) {
      alert('设备未连接');
      return;
    }

    try {
      setIsPlaying(true);
      const response = await fetch('/api/buzzer/play', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          frequency: freq,
          isRunning: true
        })
      });

      if (!response.ok) {
        throw new Error('播放失败');
      }
    } catch (error) {
      console.error('播放音调失败:', error);
      alert('播放失败: ' + error.message);
      setIsPlaying(false);
    }
  };

  const stopTone = async () => {
    try {
      const response = await fetch('/api/buzzer/play', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          frequency: 0,
          isRunning: false
        })
      });
      if (!response.ok) {
        throw new Error('停止失败');
      }
    } catch (error) {
      console.error('停止播放失败:', error);
      alert('停止失败: ' + error.message);
    } finally {
      setIsPlaying(false);
    }
  };

  // 组件卸载时尝试停止正在播放的音调
  useEffect(() => {
    return () => {
      if (isPlaying && !pendingStopOnUnmountRef.current) {
        pendingStopOnUnmountRef.current = true;
        // fire-and-forget
        fetch('/api/buzzer/play', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ frequency: 0, isRunning: false })
        }).catch(() => {});
      }
    };
  }, [isPlaying]);

  return (
    <div className="space-y-8">
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-2xl font-bold text-gray-800 mb-6 flex items-center">
          <svg className="w-8 h-8 mr-3 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3" />
          </svg>
          蜂鸣器控制
        </h2>

        {/* 基本控制（移除预设音调与时长，仅保留播放/停止） */}
        <div className="grid grid-cols-1 gap-6 mb-8">
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-700">基本控制</h3>

            <div>
              <div className="flex items-center justify-between mb-2">
                <label className="block text-sm font-medium text-gray-600">
                  频率 (Hz)
                </label>
                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    min={20}
                    max={20000}
                    step={1}
                    value={frequencyInput}
                    onChange={(e) => {
                      const val = e.currentTarget.value;
                      setFrequencyInput(val);
                      const parsed = parseInt(val, 10);
                      if (!Number.isNaN(parsed)) {
                        const clamped = Math.max(20, Math.min(20000, parsed));
                        setFrequency(clamped);
                      }
                    }}
                    onBlur={() => {
                      const parsed = parseInt(frequencyInput, 10);
                      const clamped = Number.isNaN(parsed)
                        ? frequency
                        : Math.max(20, Math.min(20000, parsed));
                      setFrequency(clamped);
                      setFrequencyInput(String(clamped));
                    }}
                    className="w-28 rounded-md border border-gray-300 px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                  <span className="text-sm text-gray-500">Hz</span>
                </div>
              </div>
              <input
                type="range"
                min="20"
                max="20000"
                step="1"
                value={frequency}
                onChange={(e) => {
                  const parsed = parseInt(e.currentTarget.value, 10);
                  setFrequency(parsed);
                  setFrequencyInput(String(parsed));
                }}
                className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer slider"
              />
              <div className="flex justify-between text-xs text-gray-500 mt-1">
                <span>20 Hz</span>
                <span>20000 Hz</span>
              </div>
            </div>

            <div className="flex items-center justify-center gap-3">
              <button
                onClick={() => playTone(frequency)}
                disabled={isPlaying}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm"
              >
                {isPlaying ? '播放中...' : '播放'}
              </button>
              <button
                onClick={stopTone}
                disabled={!isPlaying}
                className="px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm"
              >
                停止
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
